<template>
  <a-modal
    v-model:visible="visible"
    title="签名"
    width="100vw"
    title-align="start"
    :render-to-body="false"
    ok-text="确定"
    :ok-loading="loading"
    hide-cancel
    @cancel="handleCancel"
    @close="handleClose"
  >
    <div style="margin-bottom: 12px">
      <a-button size="small" type="text" @click="handleClear">清除</a-button>
    </div>
    <div class="sign-name-modal-content">
      <canvas
        id="signCanvas"
        :width="canvasStyle.width"
        :height="canvasStyle.height"
      ></canvas>
    </div>

    <template #footer>
      <a-button type="primary" :loading="loading" @click="handleOk">
        确定
      </a-button>
      <a-button :loading="loading" @click="handleCancel">取消</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, withDefaults, defineProps, computed, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import SignaturePad from 'signature_pad';
  import { apiUpload } from '@/api/common/index';

  interface Props {
    close: () => void;
    resolve: () => void;
  }
  const props = withDefaults(defineProps<Props>(), {
    close: () => {
      return () => {};
    },
    resolve: () => {
      return () => {};
    },
  });

  let type = '';
  const loading = ref<boolean>(false);
  const visible = ref<boolean>(true);
  const canvasStyle = ref<any>({});
  let signaturePad: any;

  const initCanvas = () => {
    const oCanvas: any = document.getElementById('signCanvas');
    signaturePad = new SignaturePad(oCanvas);
  };

  const handleClear = () => {
    signaturePad.clear();
  };

  const dataURLtoBlob = (dataurl: any) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    // eslint-disable-next-line no-plusplus
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime,
    });
  };

  onMounted(() => {
    setTimeout(() => {
      const dom = document.getElementById('signCanvas');
      console.log('===', dom?.offsetWidth);
      canvasStyle.value = {
        width: dom?.offsetWidth,
        height: dom?.offsetHeight,
      };
      setTimeout(() => {
        initCanvas();
      }, 500);
    }, 500);
  });

  let result = '';
  const handleOk = () => {
    if (signaturePad.isEmpty()) {
      Message.warning('请签名！');
      return;
    }

    const dataURL = signaturePad.toDataURL();

    const blob = dataURLtoBlob(dataURL);
    console.log('🚀 ~ handleOk ~ blob:', blob);
    const file = new File([blob], `${Date.now()}.${blob.type}`, {
      type: blob.type,
    });
    const formData = new FormData();
    formData.append('file', dataURLtoBlob(dataURL));
    loading.value = true;
    apiUpload(formData)
      .then((res) => {
        Message.success({
          content: '上传成功',
        });
        result = res.data.fileName;
        handleSuccess();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const handleSuccess = () => {
    type = 'reslove';
    visible.value = false;
  };

  const handleCancel = () => {
    type = 'reject';
    visible.value = false;
  };

  const handleClose = () => {
    loading.value = false;
    if (type === 'reject') {
      props.close();
    } else {
      props.resolve(result);
    }
  };
</script>

<style lang="less">
  .sign-name-modal-content {
    margin: 0 auto;
    border: 1px solid #666;
    #signCanvas {
      width: 100%;
      height: 60vh;
      background: #ffffff;
      border: none;
      box-sizing: border-box;
      overflow: hidden;
    }
  }
</style>
